package cn.itcast.bos.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.domain.transit.TransitInfo;
import cn.itcast.bos.index.WayBillIndexRepository;
import cn.itcast.bos.repository.TransitInfoRepository;
import cn.itcast.bos.repository.WayBillRepository;
import cn.itcast.bos.service.TransitInfoService;

@Service
@Transactional
public class TransitInfoServiceImpl implements TransitInfoService {

	@Autowired
	private TransitInfoRepository transitInfoRepository;
	
	@Autowired
	private WayBillRepository wayBillRepository;
	
	@Autowired
	private WayBillIndexRepository wayBillIndexRepository;

	@Override
	public void createTransit(String wayBillIds) {
		if(StringUtils.isNotBlank(wayBillIds)) {
			String[] wayBillIdArr = wayBillIds.split(",");
			for(String wayBillId : wayBillIdArr) {
				//根据运单id判断运单状态是否为待发货状态
				WayBill wayBill = wayBillRepository.findOne(Integer.parseInt(wayBillId));
				if(wayBill.getSignStatus() ==1) {
					//生成中转信息
					TransitInfo transitInfo = new TransitInfo();
					//将运输流程状态设置为（出入库中转、到达网点、开始配置、正常签收、异常）
					transitInfo.setStatus("出入库中转");
					//关联运单外键
					transitInfo.setWayBill(wayBill);
					//更改运单状态（1 待发货、 2 派送中、3 已签收、4 异常）
					wayBill.setWayBillType("2");
					//保存运输流程信息
					transitInfoRepository.save(transitInfo);
					//数据库运单数据发生变化，索引库也要跟着变化
					wayBillIndexRepository.save(wayBill);
				}
			}
		}
	}

	@Override
	public Page<TransitInfo> findAll(Pageable pageable) {
		return transitInfoRepository.findAll(pageable);
	}

}
